package com.sali.controller;

import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.sali.constants.CommonConstant;
import com.sali.entity.MockVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @description:
 * @author: sali
 * @date: 2025/2/20 下午11:58.
 * @version: 1.0
 */
@RestController
@RequestMapping(value = "/mock/sender")
@Slf4j
public class HttpMockSender {

    private static String HTTP_MOCK_RECEIVER_URL = "localhost";

    private static String HTTP_MOCK_RECEIVER_PORT = "8081";

    private static String HTTP_MOCK_RECEIVER_URL_PATH = "/mock/receiver/api/1";

    @GetMapping("/api/1")
    public Object httpSender() {
        MockVO mockVO = MockVO.builder()
                .mockIds(new String[]{"id1", "id2","1d3"})
                .mockType(1)
                .keywords(new String[]{"kw1", "kw2","kw3"}).build();

        String url = String.format("http://%s:%s%s", HTTP_MOCK_RECEIVER_URL, HTTP_MOCK_RECEIVER_PORT, HTTP_MOCK_RECEIVER_URL_PATH);
        try {
            HttpRequest httpRequest = HttpUtil.createPost(url);
            httpRequest.body(JSONUtil.parse(mockVO))
                    .timeout(10000);
            if (log.isDebugEnabled()) {
                log.debug("Start remote interface, url is {}, params is {}", url, JSONUtil.toJsonStr(mockVO));
            }
            String context = httpRequest.execute().body();
            if (StringUtils.isEmpty(context)) {
                log.warn("The request url【{}】 failed！！The returned result is empty", url);
                return false;
            }

            JSONObject jsonObject = JSONUtil.parseObj(context);
            String code = jsonObject.getStr("code");
            String message = jsonObject.getStr("message");
            if (!CommonConstant.Netty.RESULT_CODE_SUCCESS.equals(code)) {
                log.warn("【RuleDistribution】The request url 【{}】 failed！！Reason for failure： code is {}, message is {}", url, code, message);
                return false;
            } else {
                log.info("code:{}, message:{}", code, message);
                return true;
            }
        } catch (HttpException e) {
            log.warn("【RuleDistribution】Remote request failed！！ url is {}, message is {}", url, e.getMessage());
            return false;
        }
    }

}
